package com.example.mychat

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mychat.adapter.MessageAdapter
import com.example.mychat.model.Message
import com.example.mychat.model.MessageStatus
import com.example.mychat.network.ChatClient
import com.example.mychat.network.ChatManager
import kotlinx.coroutines.launch
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.view.animation.AccelerateInterpolator
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.view.ViewGroup
import android.widget.LinearLayout

class MainActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var messageInput: EditText
    private lateinit var sendIcon: ImageButton
    private lateinit var sendButtonText: TextView
    private lateinit var sendButtonContainer: FrameLayout
    private lateinit var messageAdapter: MessageAdapter
    private val messageList = mutableListOf<Message>()
    private lateinit var chatClient: ChatClient
    private lateinit var username: String
    private var isTextMode = false  // 添加状态标记

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        username = intent.getStringExtra("username") ?: run {
            Log.e("MainActivity", "没有收到用户名参数")
            finish()
            return
        }
        
        initViews()
        initChatClient()
        setupKeyboardDismiss()
        
        findViewById<TextView>(R.id.toolbarTitle).text = "聊天室 - $username"
        supportActionBar?.setDisplayShowTitleEnabled(false)
    }

    private fun setupKeyboardDismiss() {
        recyclerView.setOnTouchListener { _, _ ->
            hideKeyboard()
            false
        }
    }

    private fun hideKeyboard() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        currentFocus?.let { view ->
            imm.hideSoftInputFromWindow(view.windowToken, 0)
            view.clearFocus()
        }
    }

    private fun initViews() {
        recyclerView = findViewById(R.id.recyclerView)
        messageInput = findViewById(R.id.messageInput)
        sendIcon = findViewById(R.id.sendIcon)
        sendButtonText = findViewById(R.id.sendButton)
        sendButtonContainer = findViewById(R.id.sendButtonContainer)
        
        messageAdapter = MessageAdapter(messageList) { message, position ->
            // 重试发送消息
            retrySendMessage(message, position)
        }
        recyclerView.apply {
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = messageAdapter
        }
        
        sendIcon = findViewById(R.id.sendIcon)
        sendButtonText = findViewById(R.id.sendButton)
        sendButtonContainer = findViewById(R.id.sendButtonContainer)

        // 设置按钮的变换原点在右边
        sendButtonText.post {
            sendButtonText.pivotX = sendButtonText.width.toFloat()
        }

        messageInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                val hasText = !s.isNullOrEmpty()
                if (hasText != isTextMode) {
                    isTextMode = hasText
                    animateSendButton(hasText)
                }
            }
        })

        sendIcon.setOnClickListener { sendMessage() }
        sendButtonText.setOnClickListener { sendMessage() }
    }

    private fun initChatClient() {
        // 获取已存在的 ChatClient 实例
        chatClient = ChatManager.getCurrentClient() ?: run {
            Log.e("MainActivity", "ChatClient 未初始化")
            finish()
            return
        }

        // 只更新消息回调
        chatClient.updateMessageCallback(
            messageCallback = { message ->
                // 接收到消息的回调
                runOnUiThread {
                    if (message.startsWith("SYSTEM:")) {
                        // 处理系统消息
                        val systemMessage = message.substringAfter("SYSTEM:")
                        messageList.add(Message(systemMessage, false, MessageStatus.SYSTEM, "系统"))
                    } else {
                        // 处理普通消息，提取用户名和内容
                        val colonIndex = message.indexOf(":")
                        if (colonIndex > 0) {
                            val senderName = message.substring(0, colonIndex)
                            val content = message.substring(colonIndex + 1).trim()
                            messageList.add(Message(content, false, MessageStatus.RECEIVED, senderName))
                        }
                    }
                    messageAdapter.notifyItemInserted(messageList.size - 1)
                    recyclerView.scrollToPosition(messageList.size - 1)
                }
            },
            onConnectionError = {
                runOnUiThread {
                    Toast.makeText(this, "连接断开，请检查网络", Toast.LENGTH_SHORT).show()
                    finish()
                }
            }
        )
    }

    private fun sendMessage() {
        val messageText = messageInput.text.toString().trim()
        if (messageText.isNotEmpty()) {
            val message = Message(messageText, true, MessageStatus.SENDING, username)
            val position = messageList.size
            messageList.add(message)
            messageAdapter.notifyItemInserted(position)
            recyclerView.scrollToPosition(position)
            messageInput.text.clear()

            lifecycleScope.launch {
                try {
                    chatClient.sendMessage(messageText)
                    message.status = MessageStatus.SENT
                    messageAdapter.notifyItemChanged(position)
                } catch (e: Exception) {
                    message.status = MessageStatus.FAILED
                    messageAdapter.notifyItemChanged(position)
                }
            }
        }
    }

    private fun retrySendMessage(message: Message, position: Int) {
        message.status = MessageStatus.SENDING
        messageAdapter.notifyItemChanged(position)

        lifecycleScope.launch {
            try {
                chatClient.sendMessage(message.content)
                message.status = MessageStatus.SENT
                messageAdapter.notifyItemChanged(position)
            } catch (e: Exception) {
                message.status = MessageStatus.FAILED
                messageAdapter.notifyItemChanged(position)
            }
        }
    }

    private fun animateSendButton(hasText: Boolean) {
        val duration = 300L
        val messageInput = findViewById<EditText>(R.id.messageInput)
        val inputLayoutParams = messageInput.layoutParams as LinearLayout.LayoutParams
        
        if (hasText) {
            // 先执行图标淡出，然后执行按钮展开
            val iconFadeOut = ObjectAnimator.ofFloat(sendIcon, "alpha", 1f, 0f).apply {
                this.duration = duration / 2
                addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        sendIcon.visibility = View.INVISIBLE
                        // 图标完全消失后，开始按钮展开动画
                        startExpandAnimation()
                    }
                })
            }
            iconFadeOut.start()
        } else {
            // 先调整输入框到最终宽度
            inputLayoutParams.marginEnd = resources.getDimensionPixelSize(R.dimen.send_icon_margin)
            messageInput.layoutParams = inputLayoutParams

            // 然后执行按钮收缩动画
            val buttonCollapse = ValueAnimator.ofFloat(sendButtonText.width.toFloat(), 0f).apply {
                this.duration = duration
                interpolator = AccelerateInterpolator()
                
                addUpdateListener { animation ->
                    val value = animation.animatedValue as Float
                    val params = sendButtonText.layoutParams
                    params.width = value.toInt()
                    sendButtonText.layoutParams = params
                }
                
                addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        sendButtonText.visibility = View.INVISIBLE
                        // 重置按钮宽度
                        val params = sendButtonText.layoutParams
                        params.width = ViewGroup.LayoutParams.WRAP_CONTENT
                        sendButtonText.layoutParams = params
                        // 按钮完全收缩后，显示图标
                        sendIcon.visibility = View.VISIBLE
                        sendIcon.alpha = 1f
                    }
                })
            }
            buttonCollapse.start()
        }
    }

    private fun startExpandAnimation() {
        // 先调整输入框宽度
        val messageInput = findViewById<EditText>(R.id.messageInput)
        val inputLayoutParams = messageInput.layoutParams as LinearLayout.LayoutParams
        inputLayoutParams.marginEnd = resources.getDimensionPixelSize(R.dimen.send_button_margin)
        messageInput.layoutParams = inputLayoutParams

        // 然后执行按钮展开动画
        sendButtonText.visibility = View.VISIBLE
        sendButtonText.alpha = 1f
        
        sendButtonText.measure(
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        )
        val targetWidth = sendButtonText.measuredWidth.toFloat()
        
        val buttonExpand = ValueAnimator.ofFloat(0f, targetWidth).apply {
            duration = 300L
            interpolator = DecelerateInterpolator()
            
            addUpdateListener { animation ->
                val value = animation.animatedValue as Float
                val params = sendButtonText.layoutParams
                params.width = value.toInt()
                sendButtonText.layoutParams = params
            }
        }
        buttonExpand.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 不在这里断开连接，因为可能还需要重新连接
        // chatClient.disconnect()
    }
}